package com.vim.common.utils;

import com.vim.common.base.Constants;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Token令牌管理
 */
public class TokenManager {

    //令牌存储结构 ConcurrentHashMap：支持同步的HashMap
    public static final Map<String, Date> DATA_MAP = new ConcurrentHashMap<>();

    //申请token
    public static String applyToken(){
        String token = IdGen.token();
        DATA_MAP.put(token, new Date());
        return token;
    }

    //更新token
    public static void updateToken(String token){
        DATA_MAP.put(token, new Date());
    }

    //TOKEN是否可用
    public static boolean isTokenAvailable(String token){
        if(StringUtils.isBlank(token)){
            return false;
        }
        if(DATA_MAP.get(token) == null){
            return false;
        }
        Long between = (new Date().getTime() - DATA_MAP.get(token).getTime())/1000/60;
        if(between >= Constants.expireTime){
            DATA_MAP.remove(token);
            return false;
        }
        return true;
    }
}
